package com.chenyi.framework.web.service;

import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.domain.entity.SysShop;
import com.chenyi.common.core.domain.entity.SysUser;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.core.domain.model.LoginShop;
import com.chenyi.common.core.domain.model.LoginUser;
import com.chenyi.common.core.redis.RedisCache;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.common.utils.ip.AddressUtils;
import com.chenyi.common.utils.ip.IpUtils;
import com.chenyi.common.utils.uuid.IdUtils;
import com.chenyi.shop.service.ISysShopService;
import com.chenyi.user.service.ISysUserService;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class ShopTokenService {


    // 令牌自定义标识
    @Value("${token.shopHeader}")
    private String header;

    // 令牌秘钥
    @Value("${token.shopSecret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.shopExpireTime}")
    private int expireTime;


    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysShopService shopService;


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginShop getLoginShop(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.SHOP_LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            return redisCache.getCacheObject(userKey);
        }
        return null;
    }


    /**
     * 设置用户身份信息
     */
    public void setLoginShop(LoginShop loginShop)
    {
        if (StringUtils.isNotNull(loginShop) && StringUtils.isNotEmpty(loginShop.getToken()))
        {
            refreshToken(loginShop);
        }
    }


    /**
     * 删除用户身份信息
     */
    public void delLoginShop(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }


    /**
     * 创建令牌
     *
     * @param loginShop 用户信息
     * @return 令牌
     */
    public String createToken(LoginShop loginShop) {
        if (StringUtils.isEmpty(loginShop.getToken())){
            String token = IdUtils.fastUUID();
            loginShop.setToken(token);
        }
        setUserAgent(loginShop);
        refreshToken(loginShop);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.SHOP_LOGIN_USER_KEY, loginShop.getToken());

        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginShop
     * @return 令牌
     */
    public void verifyToken(LoginShop loginShop)
    {
        long expireTime = loginShop.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginShop);
        }
    }

    public void refreshToken(LoginShop loginShop) {
        loginShop.setLoginTime(System.currentTimeMillis());
        loginShop.setExpireTime( loginShop.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginShop.getToken());
        redisCache.setCacheObject(userKey, loginShop, expireTime, TimeUnit.MINUTES);
    }

    /**`
     * 设置用户代理信息
     *
     * @param loginShop 商户信息
     */
    public void setUserAgent(LoginShop loginShop)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginShop.setIpaddr(ip);
        loginShop.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginShop.setBrowser(userAgent.getBrowser().getName());
        loginShop.setOs(userAgent.getOperatingSystem().getName());
    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }
    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    public String getJwtToken(String token){
        Claims claims = parseToken(token);
        // 解析对应的权限以及用户信息
        return (String) claims.get(Constants.SHOP_LOGIN_TOKEN_KEY);
    }

    public static String getTokenKey(String uuid) {
        return Constants.SHOP_LOGIN_TOKEN_KEY + uuid;
    }
}
